#Image processing test bench

from PIL import Image
from PIL import ImageChops
from PIL import ImageEnhance
from PIL import ImageDraw
from PIL import ImageFilter

import time

#im = Image.open("lena.bmp")
#im = Image.open("Color_test.bmp") #Open the image into memory
im = Image.open("Object_red.bmp")
im.crop((0, 0, 300, 300))

image_size = (300, 300) #Heres a tuple!
color = (255, 0, 0)

#im.show()

red =Image.new("RGB", image_size, color)
#yellow.show()
starttime = time.time()
out = ImageChops.difference(red, im) #Now we ensure that the color is white-ish for the object we want.
out = out.convert("L") #Convert to grey scale.
out = out.resize((100,100))
#out.show()


offset = 70 #low value for offset from black. Higher values increases the error
#In the iterative version, we can implement strategies for better detection and noise reduction
#We can determine the "area" of the bounding box and determine if it is too small or big.
#If it is too small, then we can either
# - Increase the offset until some threshold
# - Declare that there is just nothing there
#If it is too big, then we can either
# - Determine that there is too much noise and lower the offset
#   eventually this will either:
#    - Get the object in our target size range
#    - Offset gets lowered and nothing gets seen
#Need to think about this some more.

#We are only interested in red or close to red images.
result = Image.eval(out, lambda x: 255 if x < offset else 0) #Get the colored image
#result.show() 

#Now we have an image that may have some noise. 
#To do this, we analyize the black and white image
filtered = result.filter(ImageFilter.MinFilter(9))
print "Time: " + str(time.time() - starttime)

#Finally, we calculate display the bounding box.
bbox = filtered.getbbox()
box_result = ImageDraw.Draw(filtered)
box_result.rectangle(bbox, outline=128)
del box_result
filtered.show()

#Finally, find the hotspot of the image
print "Bounding box: "
print bbox
hotspot = ((bbox[0] + bbox[2])/2, (bbox[1] + bbox[3])/2)
print "Hotspot: "
print hotspot
#Get a vector magnitude
#print "Offset X: " + (hotspot[0] - 150)
#print "Offset Y: " + (hotspot[1] - 150)


#out.save("lena_result" + ".bmp", "BMP") #Save the image back
